
import { handleActions as createReducer } from "redux-actions" 
import { load_todo_success, add_todo_success, remove_todo_success, modify_todo_success, modify_todo_filter,
  clear_todo_completed_success, edit_todo_success, modify_todo_name_success } from '../actions/todo.actions'


const initState = {
  todos: [],
  filter: 'all'
}

const counterReducer = createReducer({
  [load_todo_success]: (newState, action) =>({...newState, todos: action.payload}),
  [add_todo_success]: (newState, action) =>({...newState, todos: [...newState.todos, action.payload]}),
  [remove_todo_success]: (newState, action) => {
    let id = action.payload
    // 取出与id相同的下标的todo的位置
    let index = newState.todos.findIndex(todo => todo.id === id)
    // 深层拷贝todos
    let todos = JSON.parse(JSON.stringify(newState.todos))
    todos.splice(index, 1)
    return { ...newState, todos }
  },
  [modify_todo_success]: (newState, action) => {
    const params = action.payload
    // console.log((params))
    let index = newState.todos.findIndex(todo => todo.id === params.id)
    let todos = JSON.parse(JSON.stringify(newState.todos))
    todos[index].isCompleted = params.isCompleted
    return { ...newState, todos }
  },
  [modify_todo_filter]: (newState, action) => {
    // console.log(action)  {type: 'modify_todo_filter', payload: 'active'}
    return {...newState, filter: action.payload}
  },
  [clear_todo_completed_success]: (newState, action) => {
    let todos = JSON.parse(JSON.stringify(newState.todos))
    todos = todos.filter(todo => !todo.isCompleted)
    return { ...newState, todos}
  },
  [edit_todo_success]: (newState, action) => {
    const params = action.payload
    // console.log((params))
    let index = newState.todos.findIndex(todo => todo.id === params.id)
    let todos = JSON.parse(JSON.stringify(newState.todos))
    todos[index].isEditing = params.isEditing
    return { ...newState, todos }
  },
  [modify_todo_name_success]: (newState, action) => {
    const params = action.payload
    // console.log((params))
    let index = newState.todos.findIndex(todo => todo.id === params.id)
    let todos = JSON.parse(JSON.stringify(newState.todos))
    todos[index].taskName = params.taskName 
    return { ...newState, todos }
  },
},initState)


export default counterReducer